package controller

import (
	"kingbloc.dts/services"
	"kingbloc.util/util"
	"net/http"
	"strconv"
	"strings"
)

func MyApproves(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "get" {
		rep.WriteHeader(200)
		return
	}

	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(200)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(200)
		return
	}

	myApproves := service.MyApproves(myAccount.Id)
	if len(myApproves) == 0 {
		rep.WriteHeader(200)
		return
	}
	util.WriteJSON(rep, myApproves)

}

func Approves(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "get" {
		rep.WriteHeader(200)
		return
	}

	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(200)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(200)
		return
	}

	approves := service.Approves(myAccount.Id)
	if len(approves) == 0 {
		rep.WriteHeader(200)
		return
	}
	util.WriteJSON(rep, approves)

}

// 审批，是否通过申请
func Approve(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "get" {
		rep.WriteHeader(200)
		return
	}

	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(200)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(200)
		return
	}

	// 是自己直推的人发起的审批

	approveId := req.URL.Query().Get("apid")
	apid, _ := strconv.ParseInt(approveId, 10, 64)
	approve := service.Approve(apid, myAccount.Id)
	if approve == nil {
		rep.WriteHeader(403)
		return
	}

	targetAccount := service.FindAccountById(approve.ProposerAccountId)
	if targetAccount == nil {
		rep.WriteHeader(403)
		return
	}

	targetAccount.Password2 = approve.DataContent
	targetAccount.UpdateCols("passwords")
	approve.Status = 1
	approve.UpdateCols("status")
	util.WriteJSON(rep, 9)
	return

}
